//
//  DATopViewControllerUtils.m
//  SGSY
//
//  Created by 时光岁月 on 2019/8/20.
//  Copyright © 2019 SGSY. All rights reserved.
//

#import "DATopViewControllerUtils.h"
#import <UIKit/UIKit.h>
@implementation DATopViewControllerUtils
+ (UINavigationController *)topmostNavigationController {
    return [self topmostNavigationControllerFrom:[self topmostViewController]];
}

+ (UINavigationController *)topmostNavigationControllerFrom:(UIViewController *)vc {
    if ([vc isKindOfClass:[UINavigationController class]])
        return (UINavigationController *)vc;
    if ([vc navigationController])
        return [vc navigationController];
    
    return nil;
}

+ (UIViewController *)topmostViewController {
    return [self topmostViewControllerFrom:[[self baseWindow] rootViewController]
                              includeModal:YES];
}

+ (UIViewController *)topmostViewControllerFrom:(UIViewController *)viewController
                                   includeModal:(BOOL)includeModal {
    if ([viewController respondsToSelector:@selector(selectedViewController)] && [(id)viewController selectedViewController]) {
        return [self topmostViewControllerFrom:[(id)viewController selectedViewController]
                                  includeModal:includeModal];
    }
    
    if (includeModal && viewController.presentedViewController) {
        return [self topmostViewControllerFrom:viewController.presentedViewController
                                  includeModal:includeModal];
    }
    
    if ([viewController respondsToSelector:@selector(topViewController)] && [(id)viewController topViewController]) {
        return [self topmostViewControllerFrom:[(id)viewController topViewController]
                                  includeModal:includeModal];
    }
    
    return viewController;
}

+ (UIWindow *)baseWindow {
    UIWindow *window = [[[UIApplication sharedApplication] delegate] window];
    if (!window)
        window = [[UIApplication sharedApplication] keyWindow];
    
    NSAssert(window != nil, @"No window to calculate hierarchy from");
    return window;
}

@end
